<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class soft extends CI_Controller {

    var $theme_data = array(
        'layout_main' => 'layout',
        'left' => 'include/leftcp',
    );
	
    function __construct() {
        parent::__construct();
        $this->load->model("muser");
        $this->load->model("msoft");
        $this->load->model("mlicense");
        $this->load->model("mresource");
        $this->load->model("mlinkdown");
        $this->load->model("mmanufacturer");
        $this->load->model("mcategory");
        $this->load->model("mtag");
        $this->load->model("msoft_tag");
		
		$this->load->helper('form');
		
		$this->resCode = $this->msoft->resCode;
        $this->url_index = admin_url() . "soft";
        $this->folder_upload = "dataupload/soft/";
        $this->url_edit = $this->url_index . "/edit/";
        $this->url_delete = $this->url_index . "/delete/";
        $this->url_add = $this->url_index . "/edit/0";
        $this->url_search = $this->url_index . "/search";
    }

    public function index($page = 0) {
        $data = array();
		$page = ($page <= 0) ? 1 : $page;
        $config = array();
        $config['per_page'] = 20;
        $config['cur_page'] = $page;
        $config['base_url'] = $this->url_index;
        $config['first_url'] = $config['base_url'] . ".html";
		$searchData = array();
		if($this->input->cookie('search')){
		$this->db->limit($config['per_page'], ($page - 1 ) * $config['per_page']);
			$searchData = $this->search();
		}

		if($searchData != array()){
			$config['total_rows'] = $searchData['num'];
		}
		else {
			$config['total_rows'] = $this->msoft->num(1, 'SOFT_STATUS');
		}
        $this->pagination->initialize($config);
		
        
		if($searchData != array()){
			$data['datas'] = $searchData['data'];
		}
		else {
		$this->db->limit($config['per_page'], ($page - 1 ) * $config['per_page']);
		$data['datas'] = $this->msoft->getsSoft();
		}
        $data['tresource'] = $this->mresource->get($this->resCode,'RES_CODE');
        $this->theme_data["main"] = "soft/index";
        $this->template->viewAdmin($this->theme_data, $data);
    }

    function edit($softID = 0) {
        $data = array();
        $post = $this->input->post();
		$data['soft'] = $this->msoft->get($softID, 'SOFT_ID');
		if ($post) {
			$link_name = @$post['link_name'];
			$link_link = @$post['link_link'];
			$newThumbName = '';
			if($softID >0){
				$newThumbName = $data['soft']->SOFT_CODE.'-'.$data['soft']->SOFT_ID;
			}
			if($upload = $this->uploadThumb(@$data['soft']->SOFT_THUMB,$newThumbName)){
				$post['soft']['SOFT_THUMB'] = str_replace(str_replace("\\","/",FCPATH),"",$upload['upload_data']['full_path']);
			}
			
			if($uploadIcon = $this->uploadIcon(@$data['soft']->SOFT_ICON,$newThumbName)){
				$post['soft']['SOFT_ICON'] = str_replace(str_replace("\\","/",FCPATH),"",$uploadIcon['upload_data']['full_path']);
			}
			//update cache
			$post['soft']['SOFT_CACHE_MAN'] = $this->msoft->cache_man($post['soft']['MAN_ID']);
			$post['soft']['SOFT_CACHE_LICENSE'] = $this->msoft->cache_lic($post['soft']['LICE_ID']);
			$post['soft']['SOFT_CACHE_CATEGORY'] = $this->msoft->cache_cate($post['soft']['CAT_ID']);
			
            if ($softID > 0) {
				$this->mlinkdown->delete($softID, 'SOFT_ID');
                $this->msoft->update($softID, 'SOFT_ID', $post['soft']);
				
            }
			else{
				$post['soft']['USE_ID'] = $this->muser->user_id;
				$softID = $this->msoft->insert($post['soft']);
			}
			
			if(isset($link_link) && $link_link){
				for($i=0; $i<count($link_link); $i++){
					if($link_link[$i] !=''){
						$this->mlinkdown->insert(array(
								'SOFT_ID'=>$softID,
								'LINK_NAME'=>$link_name[$i],
								'LINK_LINKDOWN'=>$link_link[$i],
								'LINK_TIME_CREATE'=>time()
							));
					}
				}
			}
			
			
         redirect($this->url_edit . $softID);
        }
		
        $data['links'] = $this->mlinkdown->gets($softID, 'SOFT_ID');
		$data['sman'] = array();
		$data['slice'] = array();
		$data['scate'] = array();
        $lice = $this->mlicense->gets();
        $cate = $this->mcategory->gets(1, 'CAT_STATUS');
		if($softID >0){
		$man = $this->mmanufacturer->get(@$data['soft']->MAN_ID, 'MAN_ID');
		 $data['manName'] = $man->MAN_NAME;
		 }else {
		 $data['manName'] = '';
		 }
		if(isset($lice)){
			foreach($lice as $r){
				$data['slice'][$r->LICE_ID] = $r->LICE_NAME;
			}
		}
		if(isset($cate)){
			foreach($cate as $r){
				$data['scate'][$r->CAT_ID] = $r->CAT_NAME;
			}
		}
		
		$data['tresource'] = $this->mresource->get($this->resCode,'RES_CODE');
        $data['error'] = array('err_code' => 0, 'msg' => '');
		$this->load->model("scategory");
		$cate_tree= array();
		$categoryParent = $this->mcategory->gets(array('CAT_PARENT'=>0));
		if ($categoryParent) {
			for($i=0; $i<count($categoryParent); $i++) {
				$cate_tree[$categoryParent[$i]->CAT_ID]['name'] = $categoryParent[$i]->CAT_NAME;
				$cate_child =  $this->scategory->get_cat_format_tree($categoryParent[$i]->CAT_ID);
				$cate_tree_sub = array();
				if ($cate_child) 
				foreach ($cate_child as $cc) {
					$cate_tree_sub[$cc['CAT_ID']]['item'] = $cc;
					
					$cate_tree_sub2 = array();
					$cate_child2 =  $this->scategory->get_cat_format_tree($cc['CAT_ID']);
					if ($cate_child2) {
					foreach ($cate_child2 as $cc2) {
						$cc2['CAT_NAME'] = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$cc2['CAT_NAME'];
						$cate_tree_sub2[$cc2['CAT_ID']] = $cc2['CAT_NAME'];
					}
					
					$cate_tree_sub[$cc['CAT_ID']]['sub'] = $cate_tree_sub2;
					
					}
				}
				$cate_tree[$categoryParent[$i]->CAT_ID]['sub']=$cate_tree_sub;
			}
		}
		$data['cate_tree'] = $cate_tree;
		$data['images'] = $this->msoft->getImageDetail($softID);
		$tags = $this->msoft_tag->gets($softID,'SOFT_ID');
		 
		$arr_tag = array();
		$data["tags"] = array();
		if($tags){
			foreach($tags as $tag){
				$arr_tag[] = $tag->TAG_ID;
			}
		}
		if(count($arr_tag)>0)
			$data["tags"] = $this->mtag->where_in($arr_tag,'TAG_ID');
		
        $this->theme_data["main"] = "soft/edit";
        $this->template->viewAdmin($this->theme_data, $data);
    }
	
	function delete($softID = 0){
		if($softID > 0){
			$info = $this->msoft->get($softID, 'SOFT_ID');
			if($info->SOFT_THUMB && file_exists('./'.$info->SOFT_THUMB))
				unlink('./'.$info->SOFT_THUMB);
			if($info->SOFT_ICON && file_exists('./'.$info->SOFT_ICON))
				unlink('./'.$info->SOFT_ICON);
				
			$this->msoft->delete($softID, 'SOFT_ID');
		}
	}
	
	function uploadThumb($old_name = '', $newName = '') {
		$config = array();
		$config['upload_path'] = './'.$this->folder_upload."thumb/";
		$config['allowed_types'] = 'gif|jpg|jpeg|png';
		$config['overwrite'] = true;
		if(!is_dir($this->folder_upload))
			mkdir($this->folder_upload,0777);
			
		if(!is_dir($this->folder_upload."thumb/"))
			mkdir($this->folder_upload."thumb/",0777);

		if($newName && isset($newName) && $newName!='')
			$config['file_name']	= $newName.'-thumb';
		
		$this->load->library('upload');
		$this->upload->initialize($config);
		if ( !$this->upload->do_upload())
		{
			return false;
		}
		else
		{
			
			return array('upload_data' => $this->upload->data());
		}
	}
	
	function uploadIcon($old_name = '',$newName = '') {
		$config = array();
		$config['upload_path'] = './'.$this->folder_upload."icon/";
		$config['allowed_types'] = 'gif|jpg|png';
		$config['overwrite'] = true;
		if($newName && isset($newName) && $newName!='')
			$config['file_name']	= $newName.'-icon';
			
		if(!is_dir($this->folder_upload))
			mkdir($this->folder_upload,0777);
			
		if(!is_dir($this->folder_upload."icon/"))
			mkdir($this->folder_upload."icon/",0777);
		
		$this->load->library('upload');
		$this->upload->initialize($config);
		if ( !$this->upload->do_upload('iconsoft'))
		{
			return false;
		}
		else
		{
			//if($old_name && isset($old_name))
			//unlink('./'.$old_name);
			return array('upload_data' => $this->upload->data());
		}
	}
	function do_upload_products_image() {
        
        $softID = $this->input->post('param1');
		$config =array();
		 if(!$softID || $softID <0 || $softID ==''){
			echo "Soft ID not found !!";
			return false;
		 }
		 $soft = $this->msoft->get($softID,'SOFT_ID');
		 if(!$soft){
			echo "Soft not found !!";
			 return false;
		 }
			$config['upload_path'] = './'.$this->folder_upload.'images/';
			$config['allowed_types'] = 'gif|jpg|jpeg|png';
			$config['file_name'] = $soft->SOFT_CODE.'-'.$soft->SOFT_ID;
			
			$ext = pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION);
			if(file_exists($config['upload_path'].$config['file_name'].".".$ext)){
			for($i=1; $i<10000; $i++){
				$config['file_name'] = $soft->SOFT_CODE.'-'.$soft->SOFT_ID."-".$i;
				if(!file_exists($config['upload_path'].$config['file_name'].".".$ext))
					break;
			
				}
			}
				
			
			$this->load->library('upload', $config);
			if(!is_dir($this->folder_upload))
				mkdir($this->folder_upload,0777);
			if(!is_dir($config['upload_path']))
				mkdir($config['upload_path'],0777);
			if (!$this->upload->do_upload('Filedata'))
			{
				echo $this->upload->display_errors('<p>', '</p>');

				return false;
			}
			else
			{
				$newFile = $this->upload->data();
			}
				 $array=array(
				 	"SOFT_ID"=>$softID,
					"SOFT_IP"=>$this->input->ip_address(),
					"SOFT_TIME_CREATE"=>time(),
				 	"SOFT_PATCH"=>$this->folder_upload.'images/' . $newFile['file_name']
				 );
				  $this->db->insert("soft_images",$array);
				$newID = $this->db->insert_id();
               		 echo json_encode(array('id'=>$newID, 'link'=>base_url().$this->folder_upload.'images/' . $newFile['file_name']));
                /* end write to database */
    }
	
	function deleteimage(){
		$softImageID = $this->input->post("id");
		if($softImageID >0){
			$this->load->model("msoft_images");
			$check = $this->msoft_images->get($softImageID);
			if($check){
				if($check->SOFT_PATCH && file_exists('./'.$check->SOFT_PATCH))
					unlink('./'.$check->SOFT_PATCH);
				$this->msoft_images->delete($softImageID,'SOFTI_ID');
			}
		}
	}
	function search(){
		$post = $this->input->post();
		$data = array();
		$data['data'] = array();
		$data['num'] = 0;
		if($post){
			$s = $this->input->post('txtSearch');
			$field = $this->input->post('selFieldSearch');
			$condition = $this->input->post('selCondition');
			setcookie("search",$field."|".$s.'|'.$condition, time() + 7200);
			redirect($this->url_index);
		}
		else if($this->input->cookie('search')) {
			$str = $this->input->cookie('search');
			$str = explode("|",$str);
			if(count($str) >2){
				$field = $str[0];
				$s = $str[1];
				$condition = $str[2];
			}
			else {
				return $data;
			}
		}
			if($s){
				if($condition == '='){
					$data['data'] = $this->msoft->getsSoft($s,$field);
					$data['num'] = $this->msoft->num($s,$field);
					return $data;
				}
				else {
					$data['data'] = $this->msoft->getsLike($s,$field);
					$data['num'] = $this->msoft->numLike($s,$field);
					return $data;
				}
				
			}
	 
		return $data;
	}
	
	function clean_search(){
	setcookie ("search", "", time() - 3600);
	redirect($this->url_index);
	}
	
	function getimagelist(){
		$softID = $this->input->post("id");
		$data = array();
		if($softID && $softID>0){
			$images = $this->msoft->getImageDetail($softID);
			if($images){
			foreach($images as $image){
				$data[] = array(
					'id'=>$image->SOFTI_ID,
					'url'=>base_url().$image->SOFT_PATCH,
				);
				}
			}
		}
		return json_encode($data);
	}
	
	function ajax_getTag(){
		$data = array();
		$q = $this->input->post("s");
		if($q){
			$this->db->limit(20);
			$tags = $this->mtag->like($q,'TAG_NAME');
			if(!$tags)
				return ;
			foreach($tags as $tag){
				 $data[] = $tag->TAG_NAME;
			}
			 die(json_encode($data));
		}
	}
	function ajax_addTag(){
		$tagName = $this->input->post("s");
		$softID = $this->input->post("softid");
		if($tagName){
			$tag = $this->mtag->get($tagName,'TAG_NAME');
			$tagID = 0;
			if($tag){
				$tagID  = $tag->TAG_ID;
			}
			else {
				$tagID = $this->mtag->insert(array('TAG_NAME'=>$tagName));
			}
			$softTag = $this->msoft_tag->get(array('TAG_ID'=>$tagID, 'SOFT_ID'=> $softID));
			if(!$softTag){
				$this->msoft_tag->insert(array('TAG_ID'=>$tagID, 'SOFT_ID'=> $softID));
			}
		}
	
	}
	function ajax_removeTag(){
		$tagName = $this->input->post("s");
		$softID = $this->input->post("softid");
		if($tagName){
			$tag = $this->mtag->get($tagName,'TAG_NAME');
			$tagID = 0;
			if($tag){
				$tagID  = $tag->TAG_ID;
			}
			if($tagID >0){
				$this->msoft_tag->delete(array('TAG_ID'=>$tagID, 'SOFT_ID'=> $softID));
			}
		}
	
	}
}
